<template>
  <div class="box-container">
    <div class="header-content">
      <span class="font_size20">{{ titleName + '单' }}</span>
    </div>
    <div class="body-content mt10">
      <chiceSkuCkModel ref="chiceSkuCkModelRef" :list="gd_ls" :typeText="titleName + '单'"
        @cartSaveCallBack="cartSaveCallBack">
      </chiceSkuCkModel>
      <div class="mt20 sform-box" v-if="gd_ls && gd_ls.length > 0 && tabType == 'transfer_warehouse'">
        <el-form ref="formRef" :model="objectForm" :rules="objectRules" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="tranfer-box flex_row mb20">
                <div>
                  <span>配送方式：</span>
                  <el-dropdown trigger="click" @command="selectSfee">
                    <span class="el-dropdown-link">
                      <span class="mr5 font_size14 font_bule cursor_pointer">
                        {{objectForm.shipp_type ? sfee_list.find(item => item.id == objectForm.shipp_type).title :
                          '配送方式'}}
                      </span>
                      <i class="el-icon-arrow-down el-icon--right font_bule"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown" style="max-height: 200px;overflow-y: auto;">
                      <el-dropdown-item v-for="(sf, iindx) in sfee_list" :index="iindx" :command="sf">{{ sf.title
                      }}</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
                <div class="ml30 font_size14 flex_row storez-box">
                  <div>
                    <span>调出仓库：</span>
                    <el-select v-model="objectForm.storeid" placeholder="请选择">
                      <el-option v-for="item in warehouse2List" :key="item.id" :label="item.name"
                        :value="item.id"></el-option>
                    </el-select>
                  </div>
                  <div class="ml20">
                    <el-image style="width: 36px;" src="static/icon/transfer.svg"></el-image>
                  </div>
                  <div class="ml20">
                    <span>调入仓库：</span>
                    <el-select v-model="objectForm.storeid2" placeholder="请选择" style="border: none;">
                      <el-option v-for="item in warehouse2List" :key="item.id" :label="item.name"
                        :value="item.id"></el-option>
                    </el-select>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <el-form-item label="调库状态" prop="is2do">
                <el-select v-model="is2do" placeholder="请选择">
                  <el-option v-for="item in [{ id: '1', name: '立即调库' }, { id: '2', name: '暂不调库' }]" :key="item.id"
                    :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="调库时间" prop="atime_txt">
                <el-date-picker v-model="objectForm.atime_txt" type="datetime" placeholder="选择日期时间" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd HH:mm" :disabled="!LIMIT_STOREKEEEPER_EDIT_TIME">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="ck_orders_setting.is_seller == 1">
              <el-form-item label="仓库人员" prop="uid_cp">
                <el-select v-model="objectForm.uid_cp" placeholder="请选择" clearable :disabled="!LIMIT_STOREKEEEPER_EDIT_MANAGER">
                  <el-option v-for="item in ucp_ls_data" :key="item.id" :label="item.name"
                    :value="String(item.id)"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="打印设置" prop="isprint">
                <el-select v-model="objectForm.isprint" placeholder="请选择">
                  <el-option label="暂不打印" value="2"></el-option>
                  <el-option label="打印" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="ck_orders_setting.is_txt == 1">
              <el-form-item label="添加备注" prop="txt">
                <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="objectForm.txt" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="mt20 sform-box" v-if="gd_ls && gd_ls.length > 0 && tabType != 'transfer_warehouse'">
        <el-form ref="formRef" :model="objectForm" :rules="objectRules" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="titleName + '仓库'" prop="storeid">
                <el-select v-model="objectForm.storeid" placeholder="请选择">
                  <el-option v-for="item in warehouseList" :key="item.id" :label="item.name"
                    :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="titleName + '时间'" prop="atime_txt">
                <el-date-picker v-model="objectForm.atime_txt" type="datetime" placeholder="选择日期时间" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd HH:mm" :disabled="!LIMIT_STOREKEEEPER_EDIT_TIME">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="'仓库人员'" prop="uid_cp" v-if="ck_orders_setting.is_seller == 1">
                <el-select v-model="objectForm.uid_cp" placeholder="请选择" clearable :disabled="!LIMIT_STOREKEEEPER_EDIT_MANAGER">
                  <el-option v-for="item in ucp_ls_data" :key="item.id" :label="item.name"
                    :value="String(item.id)"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="打印设置" prop="isprint">
                <el-select v-model="objectForm.isprint" placeholder="请选择">
                  <el-option label="暂不打印" value="2"></el-option>
                  <el-option label="打印" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="tabType == 'into_warehouse' ? '收货单位' : '来货单位'" prop="customerid">
                <div class="">
                  <span class="mr10" v-if="objectForm.shipp_info.company">{{ objectForm.shipp_info.company }}</span>
                  <span class="mr5" v-if="objectForm.shipp_info.name">{{ objectForm.shipp_info.name }}</span>
                  <span class="mr5" v-if="objectForm.shipp_info.cellphone">{{ objectForm.shipp_info.cellphone }}</span>
                  <span class="mr5">
                    <span v-if="objectForm.shipp_info && objectForm.shipp_info.district">{{
                      objectForm.shipp_info.district }} </span>
                    <span v-if="objectForm.shipp_info && objectForm.shipp_info.address">{{
                      objectForm.shipp_info.address
                    }}</span>
                  </span>
                  <el-button class="ml20" type="primary" size="mini" icon="el-icon-plus"
                    @click="addChoice">选择单位</el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="ck_orders_setting.is_txt == 1">
              <el-form-item :label="titleName + '备注'" prop="txt">
                <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="objectForm.txt" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="footer-content" v-if="operations.length > 0">
      <footer-bottom :operations="operations" @operation="handleOperation" />
    </div>
    <PopCustomerSelect ref="popCustomerSelectRef" @getCustomerData="getCustomerData" />
    <PopSupperSelect ref="PopSupperSelectSelectRef" @getCustomerData="getSupperData" />
    <TxtLsDrawer ref="txtLsDrawerRef" :txt_ls="objectForm.txt_imgs" :id="cart_info.id" />
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, getCurrentInstance, watch, computed, nextTick } from '@vue/composition-api'
const { proxy } = getCurrentInstance()
import staticConst from "@/js/const/StaticConst.js"; // 权限id 
import config from "@/js/conf/Config.js"
import FooterBottom from "@/components/commV2/FooterBottom/index.vue";
import { useOrderReceiptState } from '@/pages/warehouseManage/hooks/useOrderReceiptState.js'
import chiceSkuCkModel from "@/components/commV2/chiceSkuCkModel/index.vue"
import PopCustomerSelect from "@/components/appointment/popCustomerSelect.vue";
import PopSupperSelect from "@/components/appointment/popSupperSelect.vue";
import TxtLsDrawer from "@/pages/warehouseManage/orderReceipt/components/txtLsDrawer.vue";
import accessCtrl from "@/js/limit/AccessCtrl.js"; // 检测权限

const {
  gd_ls,
  cart_info,
  tabType,
  ckOrderOrderAdd,
  query,
  box_index_key,
  isEdit,
  isCartAddFrom,
  selectedIndex,
  recordSelectedIndex,
  getEventLs,
  getSfeeLsFun,
  objectForm,
  warehouseList,
  warehouse2List,
  getCartInfoFun,
  ucp_ls_data,
  ck_orders_setting,
  sfee_list
} = useOrderReceiptState()

// 调库使用
const is2do = ref('1')

objectForm.value = {
  atime_txt: '', // 默认当前本地日期时间
  customerid: "",
  isdo: "1",
  isprint: "2",
  shipp_info: {},
  storeid: '0',
  storeid2: undefined, // 调入库仓库
  storeid_print: "",
  uid_cp: "", // 仓库人员
  txt_imgs: [],
  txt: '',
  suppid: '',
  shipp_type: '', // 配送方式
}

// into_warehouse  入库单
// out_warehouse  出库单
// transfer_warehouse  调拨单
const titleName = computed(() => {
  return tabType.value == 'into_warehouse' ? '入库' :
    tabType.value == 'transfer_warehouse' ? '调拨' :
      tabType.value == 'out_warehouse' ? '出库' : ''
})

const operations = computed(() => {
  return gd_ls.value && gd_ls.value.length > 0 ? [
    { text: '放弃开单', type: 'fqkd', class: 'danger' },
    { text: '保存草稿', type: 'bccg', class: 'orange' },
    { text: `提交`, type: 'tjjs', class: 'primary' },

  ] : []
})

const objectRules = ref({
  storeid: [
    { required: true, message: '请选择出库仓库', trigger: 'change' }
  ],
  atime_txt: [
    { required: true, message: '请选择出库时间', trigger: 'change' }
  ],
  uid_cp: [
    { required: true, message: '请选择仓库人员', trigger: 'change' }
  ],
})

const selectSfee = (item) => {
  objectForm.value.shipp_type = item.id
}

// 添加单位地址
const addChoice = () => {
  if (tabType.value == 'into_warehouse') {
    proxy.$refs.PopSupperSelectSelectRef.initData();
  } else if (tabType.value == 'out_warehouse') {
    proxy.$refs.popCustomerSelectRef.initData();
  }
}

// 选择单位
const getCustomerData = (data) => {
  objectForm.value.shipp_info = {
    ...data,
  }
  objectForm.value.customerid = data.id
}

// 选择供应商
const getSupperData = (data) => {
  objectForm.value.shipp_info = {
    address: "",
    addressee: "",
    area: "",
    cellphone: "",
    city: "",
    district: "",
    province: "",
    ...data,
  }
  objectForm.value.suppid = data.id
}

// 处理操作按钮点击
const handleOperation = (type) => {
  console.log('操作类型:', type)
  switch (type) {
    case 'fqkd': // 放弃开单
      handleCancelOrder()
      break
    case 'bccg': // 保存草稿
      handleSaveDraft()
      break
    case 'tjjs': // 提交结算
      submitHandle()
      break
    default:
      console.warn('未知操作类型:', type)
  }
}

// 放弃开单
const handleCancelOrder = () => {
  proxy.$confirm('确定要放弃当前开单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    selectedIndex.value = recordSelectedIndex.value
    isEdit.value = false
    isCartAddFrom.value = false
    getEventLs(false)
    proxy.$message({
      type: 'info',
      message: '已放弃开单'
    })
  }).catch(() => {
    // 用户取消
  })
}

// 保存草稿
const handleSaveDraft = async () => {
  // 基本验证（不包括必填项）
  if (!gd_ls.value || gd_ls.value.length === 0) {
    proxy.$message({
      message: '请先添加商品信息',
      type: 'warning',
    })
    return
  }
  proxy.$confirm('确定保存到草稿吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    let params = {
      ...objectForm.value,
      backup: 1 // 标记为草稿
    }
    try {
      ckOrderOrderAdd(params)
    } catch (error) {
      proxy.$message({
        message: '保存失败',
        type: 'error',
      })
    }
  })
}

// 提交
const submitHandle = async () => {
  if (tabType.value == 'transfer_warehouse') {
    if (!objectForm.value.shipp_type) {
      proxy.$message({
        message: '请选择配送方式',
        type: 'error',
      })
      return
    }
    if (!objectForm.value.storeid || !objectForm.value.storeid2) {
      proxy.$message({
        message: '请选择调出/调入仓库',
        type: 'error',
      })
      return
    }
    objectForm.value.isdo = is2do.value
  }
  try {
    // 表单验证
    const valid = await proxy.$refs.formRef.validate()
    if (!valid) {
      proxy.$message({
        message: '请完善表单信息',
        type: 'warning',
      })
      return
    }
    let params = {
      ...objectForm.value,
      backup: '',
    }
    if (params.storeid == '0' && tabType.value != 'transfer_warehouse') {
      params.isdo = '2'
    }
    ckOrderOrderAdd(params)
  } catch (error) {
    proxy.$message({
      message: '请完善表单信息',
      type: 'error',
    })
  }
}

// 备注
const handleTxtLs = () => {
  proxy.$refs.txtLsDrawerRef.open()
}

const resetFc = () => {
  objectForm.value.customerid = ''
  objectForm.value.suppid = ''
}
resetFc()

const cartSaveCallBack = () => {
  getCartInfoFun()
}

const LIMIT_STOREKEEEPER_EDIT_MANAGER = ref(false); //单据经手人可改
const LIMIT_STOREKEEEPER_EDIT_TIME = ref(false); //单据时间可改
const initPermission = async () => {
  LIMIT_STOREKEEEPER_EDIT_MANAGER.value =  await accessCtrl.getStorekeeperEditManagerLimit(); //单据经手人可改
  LIMIT_STOREKEEEPER_EDIT_TIME.value = await accessCtrl.getStorekeeperEditTimeLimit(); //单据时间可改
}
initPermission()

onMounted(() => {
  const setPopperStyle = () => {
    const popperElements = document.querySelectorAll('.popperx-box');
    popperElements.forEach(element => {
      element.style.paddingLeft = '0';
    });
  };
  // 立即执行一次
  setPopperStyle();
  // 由于Element UI的popover是动态生成的，需要监听DOM变化
  const observer = new MutationObserver(setPopperStyle);
  observer.observe(document.body, {
    childList: true,
    subtree: true
  });
  // 组件销毁时断开观察
  return () => {
    observer.disconnect();
  };
})

defineExpose({})

// 定义props（合并为一个调用）
defineProps({})

</script>

<style lang="scss" scoped>
.box-container {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .header-content {
    width: 100%;
    height: 40px;
    border-bottom: 2px solid #E4E7ED;
    margin-bottom: 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .body-content {
    padding: 10px 10px 0;
    flex: 1;
    overflow-y: auto;
  }

  .footer-content {
    height: 60px;
  }
}

.tranfer-box {
  padding: 0 16px 16px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.06);
  transition: box-shadow 0.3s ease;
}

.sform-box {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: box-shadow 0.3s ease;
}

.storez-box {
  border: 1px solid #caced6;
  padding: 10px 20px;
  border-radius: 6px;
  background-color: #f0f6fa;

}

.storez-box ::v-deep.el-input__inner {
  border: none !important;
  border-bottom: 1px solid #caced6 !important;
  border-radius: 0;
  background: none;
}
</style>